from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, HttpRequest, JsonResponse


class ImageCodeView(View):
    def get(self, request, uuid):
        from libs.captcha.captcha import captcha
        # text为图片验证码内容
        text, image = captcha.generate_captcha()
        print(text)
        # 将验证码存储到redis中
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')
        redis_cli.setex(uuid, 100, text)
        return HttpResponse(image, content_type='image/jpeg')


class SmsCodeView(View):
    def get(self, request, mobile):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not all([image_code, uuid]):
            return JsonResponse({'code': 400, 'errmsg': '参数不足'})

        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')
        redis_image_code = redis_cli.get(uuid)
        # 判断验证码是否过期
        if redis_image_code is None:
            return JsonResponse({'code': '400', 'errmsg': '图片验证码已过期'})
        # 判断验证码是否正确
        if redis_image_code.decode().lower() != image_code.lower():
            return JsonResponse({'code': 400, 'errmsg': '图片验证码错误'})
        # 提取短信标记，检测是否短期内发过短信验证码
        send_flag = redis_cli.get('send_flag_%s' % mobile)
        if send_flag is not None:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码发送过于频繁'})
        # 生成随机短信验证码
        from random import randint
        sms_code = '%04d' % randint(0, 9999)

        # 使用管道
        # 1.新建一个管道
        pipeline = redis_cli.pipeline()
        # 2.管道收集指令
        # 保存短信验证码
        pipeline.setex(mobile, 300, sms_code)
        # 存储标记
        pipeline.setex('send_flag_%s' % mobile, 120, 1)
        # 3.管道执行指令
        pipeline.execute()

        # # 将短信验证码保存到redis中
        # redis_cli.setex(mobile, 300, sms_code)
        # # 在redis中存储send_code标记，表示已发送信息
        # redis_cli.setex('send_flag_%s' % mobile, 120, 1)
        # # 发送验证码
        # from libs.yuntongxun.sms import CCP
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)  # 由于测试试用只能发送四位数的验证码

        from celery_tasks.sms.tasks import celery_send_sms_code

        celery_send_sms_code.delay(mobile, sms_code)

        # 返回响应
        return JsonResponse({'code': '0', 'errmsg': 'ok'})
